package com.lvw.weather.gateway.config;

import com.lvw.weather.gateway.filter.AccessFilter;
import com.netflix.zuul.FilterFileManager;
import com.netflix.zuul.FilterLoader;
import com.netflix.zuul.groovy.GroovyCompiler;
import com.netflix.zuul.groovy.GroovyFileFilter;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.netflix.zuul.filters.discovery.PatternServiceRouteMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
/* 开启ZuulFilterProperties上的ConfigurationProperties */
@EnableConfigurationProperties(ZuulFilterProperties.class)
public class ZuulConfiguration {

    /* 为符合pattern的serviceId的服务创建路由 */
    @Bean
    public PatternServiceRouteMapper patternServiceRouteMapper() {
        return new PatternServiceRouteMapper(
                "(?<name>^.+)-(?<version>v.+$)",
                "${version}-${name}");
    }

    /* 自动加载groovy类型的filter */
    @Bean
    public FilterLoader filterLoader(ZuulFilterProperties zuulFilterProperties) {

        FilterLoader filterLoader = FilterLoader.getInstance();
        filterLoader.setCompiler(new GroovyCompiler());

        FilterFileManager.setFilenameFilter(new GroovyFileFilter());
        try {
            FilterFileManager.init(zuulFilterProperties.getInterval()
                    , zuulFilterProperties.getRoot());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return filterLoader;

    }

    @Bean
    public AccessFilter accessFilter() {  // Customized filter
        return new AccessFilter();
    }

}
